<?php

namespace app\command;

use app\model\DistributionSetting;
use app\model\Order;
use app\model\User;
use app\model\UserInvite;
use app\model\UserUpgradeLogModel;
use Exception;
use think\console\Command;
use think\console\Input;
use think\console\Output;

class TestCommand extends Command
{
	protected function configure()
	{
		$this->setName('test')
			->setDescription('test');
	}

	/**
	 * @throws Exception
	 * 执行一次性任务脚本
	 */
	protected function execute(Input $input, Output $output)
	{
		$setting = DistributionSetting::where('uuid', 'setting')->find();
		if (!$setting) {
			return;
		}
		$levelList = json_decode($setting['value'], true);

		// 查询用户等级为v2和v3的用户列表
		$userList = User::field('id,token,level,privilege_time')
			->whereIn('level', [
				User::LEVEL_V2,
				User::LEVEL_V3,
			])->select()
			->toArray();

		$tokenList = array_column($userList, 'token');
		$userIds   = array_column($userList, 'id');

		// 查询用户的邀请数量
		$inviteUserCount    = UserInvite::field('token, count(token) as total')
			->whereIn('token', $tokenList)
			->group('token')
			->select()
			->toArray();
		$inviteUserCountMap = array_column($inviteUserCount, null, 'token');

		// 查询用户下单数量
		$orderCount    = Order::field('user_id, count(*) as total')
			->whereIn('user_id', $userIds)
			->group('user_id')
			->where('commission_status', Order::COMMISSION_STATUS_COMPLETE)
			->select()
			->toArray();
		$orderCountMap = array_column($orderCount, null, 'user_id');

		foreach ($userList as $item) {

			$inviteCount = $inviteUserCountMap[$item['token']] ?? [];
			$orderCount  = $orderCountMap[$item['id']] ?? [];

			if ($item['level'] == User::LEVEL_V2) {
				$this->levelHandle($item, $inviteCount, $orderCount, $levelList[1],
					User::LEVEL_V1, User::LEVEL_V2);
			}

			if ($item['level'] == User::LEVEL_V3) {
				$this->levelHandle($item, $inviteCount, $orderCount, $levelList[1],
					User::LEVEL_V1, User::LEVEL_V2);
				$level['invite_count'] = $levelList[1]['invite_count'] + $levelList[2]['invite_count'];
				$level['order_count']  = $levelList[1]['order_count'] + $levelList[2]['order_count'];
				$this->levelHandle($item, $inviteCount, $orderCount, $level,
					User::LEVEL_V2, User::LEVEL_V3);
			}

		}

	}

	/**
	 * @throws Exception
	 */
	private function levelHandle($userInfo, $inviteCount, $orderCount, $level, $beforeLevel, $afterLevel): void
	{
		$inviteList = [];
		// 判断是哪个数量满足了升级条件
		if (!empty($inviteCount) && $inviteCount['total'] >= $level['invite_count']) {
			// 查询邀请记录，id正序，查询满足升级条件的条数
			$inviteList = UserInvite::field('id,create_time')
				->where('token', $userInfo['token'])
				->order('id asc')
				->limit($level['invite_count'])
				->select()
				->toArray();
		}

		$orderList = [];
		if (!empty($orderCount) && $orderCount['total'] >= $level['order_count']) {
			// 查询订单记录，id正序，查询满足升级条件的条数
			$orderList = Order::field('id,create_time')
				->where('user_id', $userInfo['id'])
				->where('commission_status', Order::COMMISSION_STATUS_COMPLETE)
				->order('id asc')
				->limit($level['order_count'])
				->select()
				->toArray();
		}

		$lastInvite     = end($inviteList);
		$lastOrder      = end($orderList);
		$lastInviteTime = 0;
		$lastOrderTime  = 0;
		if ($lastInvite) {
			$lastInviteTime = strtotime($lastInvite['create_time']);
		}
		if ($lastOrder) {
			$lastOrderTime = strtotime($lastOrder['create_time']);
		}

		// 判断满足邀请条件时的数据，和满足订单条件时的数据，哪个更先创建，就认为升级类型就是哪个
		$createUserUpgradeLog = [
			'user_id'      => $userInfo['id'],
			'type'         => UserUpgradeLogModel::TYPE_UPGRADE,
			'before_level' => $beforeLevel,
			'after_level'  => $afterLevel,
			'created_at'   => date('Y-m-d H:i:s'),
			'updated_at'   => date('Y-m-d H:i:s'),
		];

		if (($lastInviteTime < $lastOrderTime && $lastInviteTime != 0) || $lastOrderTime == 0) {
			$createUserUpgradeLog['source_type'] = UserUpgradeLogModel::SOURCE_TYPE_INVITE_UPGRADE;
		} else if (($lastOrderTime < $lastInviteTime && $lastOrderTime != 0) || $lastInviteTime == 0) {
			$createUserUpgradeLog['source_type'] = UserUpgradeLogModel::SOURCE_TYPE_CRATE_ORDER_UPGRADE;
		} else {
			throw new Exception('数据异常');
		}

		if ($afterLevel == User::LEVEL_V3) {
			$createUserUpgradeLog['expired_at'] = date('Y-m-d H:i:s', $userInfo['privilege_time']);
		}

		// 查询数据是否存在
		$userUpgradeLog = UserUpgradeLogModel::field('id')
			->where('user_id', $userInfo['id'])
			->where('type', UserUpgradeLogModel::TYPE_UPGRADE)
			->where('before_level', $beforeLevel)
			->where('after_level', $afterLevel)
			->find();
		if (empty($userUpgradeLog)) {
			UserUpgradeLogModel::create($createUserUpgradeLog);
		}
	}
}